<?php
require_once ( "Channel.class.php" ) ;


function pushtest(){
    echo "Push Test";
}

function error_output ( $str ) 
{
	echo  $str .'<br><br>';
}

function right_output ( $str ) 
{
    echo $str .'<br><br>';
}


//推送android设备消息
function android_push_message($user_id, $title, $msg, $data)
{
    //请开发者设置自己的apiKey与secretKey
    $apiKey = "hGvERDTisLXpNRWIuM7pld7W";
    $secretKey = "PDV5bCfU4dl0rmtO5aYbW1agTKnLcI5U";

    $channel = new Channel ( $apiKey, $secretKey ) ;
    //推送消息到某个user，设置push_type = 1; 
    //推送消息到一个tag中的全部user，设置push_type = 2;
    //推送消息到该app中的全部user，设置push_type = 3;
    $push_type = 1; //推送单播消息
    $optional[Channel::USER_ID] = $user_id; //如果推送单播消息，需要指定user
    //optional[Channel::TAG_NAME] = "xxxx";  //如果推送tag消息，需要指定tag_name

    //指定发到android设备
    $optional[Channel::DEVICE_TYPE] = 3;
    //指定消息类型为通知
    $optional[Channel::MESSAGE_TYPE] = 1;
    //通知类型的内容必须按指定内容发送，示例如下：
    $message = '{ 
            "title": "'.$title.'",
            "description": "'.$msg.'",
            "notification_basic_style":7,
            "custom_content": '.json_encode($data).'
        }';
    
    $message_key = "msg_key";
    $ret = $channel->pushMessage ( $push_type, $message, $message_key, $optional ) ;
    if ( false === $ret )
    {
        error_output ( 'WRONG, ' . __FUNCTION__ . ' ERROR!!!!!' ) ;
        error_output ( 'ERROR NUMBER: ' . $channel->errno ( ) ) ;
        error_output ( 'ERROR MESSAGE: ' . $channel->errmsg ( ) ) ;
        error_output ( 'REQUEST ID: ' . $channel->getRequestId ( ) );
    }
    else
    {
        right_output ( 'SUCC, ' . __FUNCTION__ . ' OK!!!!!' ) ;
        right_output ( 'result: ' . print_r ( $ret, true ) ) ;
    }
}


//推送android设备消息
function android_push_messages($msg, $data)
{
    //请开发者设置自己的apiKey与secretKey
    $apiKey = "hGvERDTisLXpNRWIuM7pld7W";
    $secretKey = "PDV5bCfU4dl0rmtO5aYbW1agTKnLcI5U";

    $channel = new Channel ( $apiKey, $secretKey ) ;
	//推送消息到某个user，设置push_type = 1; 
	//推送消息到一个tag中的全部user，设置push_type = 2;
	//推送消息到该app中的全部user，设置push_type = 3;
	$push_type = 3; //推送单播消息
	// $optional[Channel::USER_ID] = $user_id; //如果推送单播消息，需要指定user
	// $optional[Channel::TAG_NAME] = "xxxx";  //如果推送tag消息，需要指定tag_name

	//指定发到android设备
	$optional[Channel::DEVICE_TYPE] = 3;
	//指定消息类型为通知 0 ：消息（透传） 1：通知
	$optional[Channel::MESSAGE_TYPE] = 1;
	//通知类型的内容必须按指定内容发送，示例如下：
	$message = '{ 
			"title": "摇吧 中奖通知",
			"description": "'.$msg.'",
			"notification_basic_style":7,
            "custom_content": '.json_encode($data).'
 		}';
	
	$message_key = "msg_key";
    $ret = $channel->pushMessage ( $push_type, $message, $message_key, $optional ) ;
    if ( false === $ret )
    {
        error_output ( 'WRONG, ' . __FUNCTION__ . ' ERROR!!!!!' ) ;
        error_output ( 'ERROR NUMBER: ' . $channel->errno ( ) ) ;
        error_output ( 'ERROR MESSAGE: ' . $channel->errmsg ( ) ) ;
        error_output ( 'REQUEST ID: ' . $channel->getRequestId ( ) );
    }
    else
    {
        right_output ( 'SUCC, ' . __FUNCTION__ . ' OK!!!!!' ) ;
        right_output ( 'result: ' . print_r ( $ret, true ) ) ;
    }
}

  
  

function ios_push_message($token,$count,$data,$dev,$message='测试推送数据接口'){
    // 得到deviceToken
    $deviceToken = $token;
    // 密钥:
    $passphrase = 'youdao';
    // 要推送的消息:
    $sound = 'default';
     
    $ctx = stream_context_create();
    if($dev===0){
        stream_context_set_option($ctx, 'ssl', 'local_cert', Yii::app()->basePath.'/push/pem/pro.pem');
        stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
        $fp = stream_socket_client(  'ssl://gateway.push.apple.com:2195', $err,  $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
    }else{
        stream_context_set_option($ctx, 'ssl', 'local_cert', Yii::app()->basePath.'/push/pem/dev.pem');
        stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
        $fp = stream_socket_client(  'ssl://gateway.sandbox.push.apple.com:2195', $err,  $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
    }
       
    $body['aps'] = array(
            'alert' => $message,
            'sound' => $sound,
            "badge" => $count
            );
    $body['data'] = $data;
    // 转换json
    $payload = json_encode($body);

    echo '<br>payload length = '.strlen($payload);

    $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
    $fwrite = fwrite($fp, $msg, strlen($msg));

    if(!$fwrite) {
        echo "send success";
    } else {
        // echo $fwrite;
        $tv_sec = 1;
        $tv_usec = null;
        $r = array($fp); $we = null; 
        $numChanged = stream_select($r, $we, $we, $tv_sec, $tv_usec);

        if(false===$numChanged) {
            echo("Failed selecting stream to read.");
        }
        
        else if($numChanged>0) {
            $command = ord(fread($fp, 1));
            $status = ord(fread($fp, 1));
            // $identifier = implode('', unpack("N", fread($fp, 4)));
            $statusDesc = array(
                0 => 'No errors encountered',
                1 => 'Processing error',
                2 => 'Missing device token',
                3 => 'Missing topic',
                4 => 'Missing payload',
                5 => 'Invalid token size',
                6 => 'Invalid topic size',
                7 => 'Invalid payload size',
                8 => 'Invalid token',
                255 => 'None (unknown)',
            );
            echo("APNS responded with command($command) status($status).");

            if($status>0) {
                $desc = isset($statusDesc[$status])?$statusDesc[$status]: 'Unknown';
                echo("APNS responded with error for pid($identifier). status($status: $desc)");
                // The socket has also been closed. Cause reopening in the loop outside.
            }
        }  
    }
    fclose($fp);
}

?>